<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!--    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.10.0/jquery.min.js"></script>-->
    <script src="./js/papaparse.js"></script>
    <script src="./js/ponyfill.min.js"></script>
    <script src="./js/StreamSaver.min.js"></script>
</head>
<body>
    <div id="app">

        <form enctype="multipart/form-data" method="post">
            <h1>Upload Test</h1>
            <input type="file" multiple @change="fileChange($event.target.files)" id="file1">
        </form>

        <p>Preview:</p>
        <table>
            <tr>
                <th v-for="field in fields">{{field}}</th>
            </tr>
            <tr v-for="record in preview">
                <td v-for="field in fields">{{record[field]}}</td>
            </tr>
        </table>

        <p>Fields</p>
        <div v-for="field in fields">
            <input type="checkbox" :value="field" :id="field" v-model="checkedFields" >
            <label :for="field">{{field}}</label>
        </div>

        <p>{{outFields}}</p>
        <button @click="convert">Convert</button>
    </div>
    <script>
        function appendToFilename(filename, string){
            const dotIndex = filename.lastIndexOf(".");
            if (dotIndex === -1)
                return filename + string;
            else
                return filename.substring(0, dotIndex) + string + filename.substring(dotIndex);
        }

        const encode = TextEncoder.prototype.encode.bind(new TextEncoder)

        const app = new Vue({
            el: '#app',
            data: {
                preview: [],
                fields: [],
                checkedFields: [],
                csvFile: undefined,
            },
            methods: {
                fileChange: function (files) {
                    Papa.parse(files[0], {
                        header: true,
                        preview: 10,
                        complete: (results) => {
                            this.preview = results.data
                            this.fields = results.meta.fields
                            console.log("results meta => ", results.meta)
                        }
                    })

                    this.csvFile = files[0]
                },
                convert: function () {
                    const outFilename = appendToFilename(this.csvFile.name, '-out')

                    const fileStream = streamSaver.createWriteStream(outFilename, {})
                    const writer = fileStream.getWriter()

                    const csvHeader = this.outFields.join(',') + '\n'
                    writer.write(encode(csvHeader))

                    Papa.parse(this.csvFile, {
                        header: true,
                        worker: true,
                        skipEmptyLines: true,
                        chunk: (results) => {
                            const data = results.data.map((record) => {
                                return this.outFields.map((field) => record[field]).join(',') + '\n'
                            }).join('')

                            writer.write(encode(data))
                        },
                        complete: function () {
                            writer.close()
                            console.log("it done!")
                        }
                    })
                }
            },
            computed: {
                outFields: function () {
                    return this.fields.filter(f => this.checkedFields.includes(f))
                }
            }
        })        
    </script>
</body>
</html>